package com.example.administrator.shzs.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.activity.BaseActivity;
import com.example.administrator.shzs.activity.LogInActivity;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.entity.CollectShopData;
import com.example.administrator.shzs.entity.MerchantData.ListBean;
import com.example.administrator.shzs.entity.OrderData;
import com.example.administrator.shzs.url.Contents;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 到店支付页面
 */
public class OfflinePayActivity extends BaseActivity {

    private TextView ShopTitle;
    private EditText Money;
    private Button button;
    private ImageView shop_back;

    private CircleImageView shop_image;


    //商家名字
    private String shopname;
    private String image;
    private String shopid;
    //获取金额
    private String pice;

    private OrderData orderData;

    //        获取数据 商家经纬度
    private double latitude;
    private double longitude;

    private boolean isHomeFragment = false;
    private boolean isAttentionShopActivity = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_pay);
        MyApplication.app.activityList.add(this);


        ShopTitle = (TextView) findViewById(R.id.ShopTitle);
        Money = (EditText) findViewById(R.id.Money);
        button = (Button) findViewById(R.id.shop_button);
        shop_image = (CircleImageView) findViewById(R.id.shop_image);
        shop_back = (ImageView) findViewById(R.id.shop_back);
        // 接收
        getData();

        shop_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MyApplication.app.getUserId() != null) {
                    if (Money.length() == 0) {

                        Toast.makeText(OfflinePayActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
                    } else {
                        String price = Money.getText().toString().trim();
                        latitude = MyApplication.app.getLatitude();
                        longitude = MyApplication.app.getLongitude();
                        submitOrder(price);
                    }

                } else {
                    startActivity(new Intent(OfflinePayActivity.this, LogInActivity.class));
                }

            }
        });
    }


    /**
     * 提交订单
     *
     * @param price
     */
    private void submitOrder(final String price) {

        //        获取当前时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date data = new Date(System.currentTimeMillis());
        String str = formatter.format(data);

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("CustomerName", "");
        map.put("Receiver", "长捷网络科技");
        map.put("Address", "生活当面付");
        map.put("Phone", "18888888888");
        map.put("Mobilephone", "18888888888");
        map.put("Remark", "骑手");
        map.put("sendfree", "0");
        map.put("state", "0");
        map.put("ulng", MyApplication.app.getLongitude() + "");
        map.put("ulat", MyApplication.app.getLatitude() + "");
        map.put("UserID", MyApplication.app.getUserId());
        map.put("bid", "0");
        map.put("PayMode", "1");
        map.put("isuercard", "0");
        map.put("Ordersource", "2");
        map.put("sendtype", "1");
        map.put("GainTime", str);
        map.put("PayPassword", "");
        map.put("DataID", shopid);
        map.put("foodprice", price);
        Gson gson = new Gson();
        String json = gson.toJson(map);

        RequestBody params = new FormBody.Builder().add("ordermodel", "[" + json + "]").build();

        String url = Contents.DANGMIAN_PAY;

        Request request = new Request.Builder().url(url).post(params).build();


        Contents.okhttp.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String s = response.body().string();
                orderData = JSON.parseObject(s, OrderData.class);
                //获取后台提供的订单号
                String orderId = orderData.getOrderid();
                int state = orderData.getOrderstate();
                pice = orderData.getTotalprice();
                String mms = orderData.getMsg();
                if (state == 1) {
                    payday(orderId);
                } else {
                    Toast.makeText(OfflinePayActivity.this, mms, Toast.LENGTH_SHORT).show();
                }

            }
        });

    }


    private void payday(String orderId) {

        String url = Contents.PAY_ORDERID_URL;

        RequestBody requestBody = new FormBody.Builder().
                add("orderid", orderId)
                .add("price", pice).build();

        Request request = new Request.Builder().url(url).post(requestBody).build();

        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String s = response.body().string();

                String price = orderData.getTotalprice();

                try {
                    JSONObject jsonObject = new JSONObject(s);
                    int state = jsonObject.getInt("state");
                    if (state == 1) {
                        //生成支付宝订单号
                        String orderid = jsonObject.getString("batch");
                        Intent payOrder = new Intent(OfflinePayActivity.this, PayOrderActivity.class);
                        payOrder.putExtra("shopName", shopname);//商家名
                        payOrder.putExtra("shopImage", image);//商家图片
                        payOrder.putExtra("orderId", orderid);//订单Id
                        payOrder.putExtra("priceAll", price);//总价
                        startActivity(payOrder);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    /**
     * 商家获取数据
     */
    private void getData() {

        Intent intent = getIntent();
        isHomeFragment = intent.getBooleanExtra("HomeFragment", false);
        isAttentionShopActivity = intent.getBooleanExtra("AttentionShopActivity", false);

        if (isHomeFragment) {//首页跳转过来的
            //    接收变量
            ListBean mermerchantdata = (ListBean) intent.getSerializableExtra("merchantdata");
            shopname = mermerchantdata.getTogoName();
            image = mermerchantdata.getIcon();
            shopid = mermerchantdata.getDataID();

        } else if (isAttentionShopActivity) {//收藏店家跳转过来的

            CollectShopData.ListBean bean = (CollectShopData.ListBean) intent.getSerializableExtra("ListBean");
            shopname = bean.getTogoName();
            image = bean.getIcon();
            shopid = bean.getDataID();

        } else {//商家界面跳转过来的

            shopname = intent.getStringExtra("ShopName");
            image = intent.getStringExtra("ShopImage");
            shopid = intent.getStringExtra("ShopId");

        }
        ShopTitle.setText(shopname);
        Picasso.with(this).load(image).into(shop_image);

    }
}
